package cn.lcl.util;

import cn.lcl.bean.po.Student;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by licho on 2017/8/17 0017.
 */
public class FormBeanUtil {
    /**
     *
     * @param request   当前请求
     * @param response  当前响应
     * @param type  封装好的fornbean
     * @param <T>
     * @return
     */
    public static <T>  T mappingParameter(Class<T> type, HttpServletRequest request, HttpServletResponse response){
        T obj= null;
        try {
            obj = type.newInstance();
            Enumeration<String> names = request.getParameterNames();
            Map<String,Method> map=parseClass(type);
            while(names.hasMoreElements()){
                String param=names.nextElement();//
                if(!map.containsKey(param))
                    throw  new RuntimeException("在Bean"+type.getName()+"中不存在属性"+param+"的getter方法");
                String[] val = request.getParameterValues(param);//
                if(val.length==1){
                    //简单javabean 属性
                        BeanUtils.setProperty(obj,param,val[0]);
                }else{
                    if(map.containsKey(param))
                        BeanUtils.setProperty(obj,param,val);
                }
            }
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return obj;
    }

    private static Map<String,Method> parseClass(Class<?> type){
        Map<String,Method> result=new HashMap<>();
        Method[] setter=type.getDeclaredMethods();
        for(Method m:setter){
            if(m.getName().startsWith("set")){
              StringBuilder build=new StringBuilder();
              char c=m.getName().charAt(3);
              c+=32;
              build.append(c).append(m.getName().substring(4));
              result.put(build.toString(),m);
            }
        }
        return  result;
    }

    public static void main(String[] args) {
        Map<String, Method> map = parseClass(Student.class);
        System.out.println(map);
    }
}
